package com.g9.blog.service.impl;

import com.g9.blog.common.Response;
import com.g9.blog.common.Result;
import com.g9.blog.entity.Admin;
import com.g9.blog.repository.AdminRepository;
import com.g9.blog.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Auther: Graycat
 * @Date: 2020/9/15 14:50
 * Create by lwj.
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminRepository adminRepository;
    @Value("${lalala.admin-path}")
    String adminPath;

    public void save(Admin admin) {
        adminRepository.save(admin);
    }

    @Override
    public void deleteById(int adminid) {
        adminRepository.deleteById(adminid);
    }

    @Override
    public Admin findById(int adminId) {
        return adminRepository.findById(adminId);
    }

    @Override
    public List<Admin> findAll() {
        return adminRepository.findAll();
    }

    // 上传管理员的头像(更改管理员表中的icon字段)
    public Result updateAdminIcon(MultipartFile file, Admin admin) {
        String path = uploadIcon(file);
        if (path==""||path==null){
            return Response.makeErrRsp("更改失败");
        }
        admin.setIcon(path);
        adminRepository.save(admin);
        return  Response.makeOKRsp("更改头像成功.");
    }

    @Override
    public Admin findByUsername(String username) {
        return adminRepository.findByUsername(username);
    }

    // 上传头像到服务器,成功就返回路径，失败返回null
    public String uploadIcon(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return "文件格式错误，要求为jpg,jpeg,gif,png.";
        }
        // 根据时间戳命名文件
        String fileName = new Date().getTime()+"."+suffix;
        // 文件保存路径
        String filePath = adminPath;

        File testfile = new File(filePath);
        // 若不存在myimg文件夹，则创建文件夹
        if (!testfile.exists()) {
            testfile.mkdir();
        }
        File dest = new File(filePath + fileName);
        System.out.println("文件存储位置：" + filePath + fileName);
        try {
            file.transferTo(dest);    //保存文件到本地的filepath
            //成功返回地址src
            return filePath+fileName;
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("上传失败");
        }
        return null;
    }
}
